<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body style="height: 10000px;">

</body>
<script>
    // 防抖代码 防止连续点击
    function debounce(fn, wait) {
        var timeout = null;
        return function () {
            console.log('timeout------>>', timeout)
            if (timeout !== null) { // 连续触发只执行一次
                clearTimeout(timeout);
            }
            timeout = setTimeout(fn, wait);
        }
    }
    // 处理函数
    function handle() {
        console.log(Math.random());
    }
    // 滚动事件
    window.addEventListener('scroll', debounce(handle, 1000));


    function throttle(func, gutter) {
        let pre = Date.now()
        return function () {
            const context = this
            const now = Date.now()
            if (now - pre > gutter) {
                func.apply(context, arguments)
                pre = Date.now()
            }
        }
    }

    // 定时器节流
    // function throttle(func, gutter) {
    //     let timmer = null
    //     return function () {
    //         const context = this
    //         const args = arguments
    //         timmer = setInterval(() => {
    //             func.apply(context, args)
    //             timmer = null
    //         }, gutter)
    //     }
    // }

    // 时间戳+定时器

    var throttle = function (func, delay) {
        var timer = null;
        var startTime = Date.now();
        return function () {
            var curTime = Date.now();
            var remaining = delay - (curTime - startTime);
            var context = this;
            var args = arguments;
            clearTimeout(timer);
            if (remaining <= 0) { //保证第一次执行
                func.apply(context, args);
                startTime = Date.now();
            } else {// 保证最后一次执行
                timer = setTimeout(() => {
                    func()
                }, remaining);
            }
        }
    }

    // 滚动事件
    window.addEventListener('scroll', throttle(handle, 1000));
</script>

</html>